import numpy as np

'''
1.初始化生成城市坐标(坐标范围在0-1000内)
2.初始化城市间的距离矩阵(二维矩阵)
'''


def index_dict_init(num):
    """
    初始化城市坐标字典, 城市的标号从0到num-1, 字典的key是城市标号, value是城市的坐标
    :param num: 城市的数量
    :return: 字典
    """
    index_dict = {}
    # 城市的标号从0到num-1, 字典的key是城市标号, value是城市的坐标
    for i in range(0, num):
        tmp_key = i
        tmp_value = []
        tmp_x = np.random.uniform(0, 1000)
        tmp_y = np.random.uniform(0, 1000)
        tmp_value.append(tmp_x)
        tmp_value.append(tmp_y)
        # 向字典中添加城市
        index_dict.update({tmp_key: tmp_value})
    return index_dict


def get_distance(from_value, to_value):
    """
    计算欧式距离函数
    :param from_value: "[x1, y1]"
    :param to_value: "[x2, y2]"
    :return: dist
    """
    x1 = from_value[0]
    y1 = from_value[1]
    x2 = to_value[0]
    y2 = to_value[1]
    dist = np.sqrt(np.power(x1 - x2, 2) + np.power(y1 - y2, 2))
    return dist


def distance_matrix_init(index_dict, num):
    """
    计算城市间距离矩阵
    :param index_dict:
    :param num:
    :return:
    """
    dist_mat = np.zeros([num, num])
    for i in range(0, num):
        from_value = index_dict.get(i)
        for j in range(0, num):
            to_value = index_dict.get(j)
            dist_mat[i][j] = get_distance(from_value, to_value)
            # 自己和自己是0, 对角线对称点相同
            dist_mat[j][i] = dist_mat[i][j]
    return dist_mat


if __name__ == '__main__':
    num = 15
    city_dict = index_dict_init(num)
    print(city_dict)
    dist_mat = distance_matrix_init(city_dict, num)
    print(dist_mat)
